﻿using System;
using System.CodeDom.Compiler;
using System.Text;
using OperationPlugins.Applications.Models;

namespace OperationPlugins.Applications
{
    /// <summary>
    /// The exception that is thrown when a fatal error occurs inside Sandbox.
    /// </summary>
    internal sealed class SandboxException : Exception
    {
        internal SandboxException(string message)
            : base(message)
        {
        }

        internal SandboxException(string message, Exception innerException) : base(message, innerException)
        {            
        }

        internal SandboxException(CompilerErrorCollection errors, AppInstance appInstance)
            : base(GetCompilerErrors(errors, appInstance))
        {
        }

        private static string GetCompilerErrors(CompilerErrorCollection errors, AppInstance appInstance)
        {
            var s = new StringBuilder();

            s.Append(string.Format("Failed to compile a sandbox runner for application {0}.", appInstance.AppId));

            foreach (CompilerError error in errors)
            {
                s.AppendLine(Environment.NewLine);
                s.Append(string.Format("{0} {1}: {2}", error.IsWarning ? "warning" : "error", error.ErrorNumber, error.ErrorText));
            }

            return s.ToString();
        }

    }
}
